package com.jianguozh.difs.framework.security.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.common.constant.ApiErrorCode;
import com.jianguozh.difs.framework.security.AuthenticatedUser;
import com.jianguozh.difs.framework.utils.ServletUtils;
import com.jianguozh.difs.framework.utils.TokenUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/11 9:07
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        try {
            String token = TokenUtils.parseToken(request);
            if (StrUtil.isNotBlank(token)) {
                AuthenticatedUser authenticatedUser = TokenUtils.parseAuthorizedUser(token);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(authenticatedUser, null, authenticatedUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            chain.doFilter(request, response);
        } catch (ExpiredJwtException e) {
            ServletUtils.renderString(response, JSONUtil.toJsonStr(R.failed(ApiErrorCode.CREDENTIALS_EXPIRED)));
        }

    }

}
